package com.dempsey.gateway.filter;

import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import com.alibaba.fastjson.JSON;
import com.dempsey.api.model.LoginUser;
import com.dempsey.common.security.constant.SecurityConstants;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import reactor.core.publisher.Mono;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

/**
 * 4. 请求通过后的额外操作处理
 *
 * @author zhe.xiao
 * @date 2021-04-13 15:01
 * @description
 */
public class ScFilter implements WebFilter {

    private final static Log log = LogFactory.get();

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        log.info("4. 请求通过后的额外操作处理");
        if (null != authentication) {
            LoginUser loginUser = (LoginUser) authentication.getPrincipal();
            log.info("loginUser：{}", loginUser);
            String loginUserJsonString = JSON.toJSONString(loginUser);
            String loginUserJsonStringEncodeUTF8 = null;
            try {
                loginUserJsonStringEncodeUTF8 = URLEncoder.encode(loginUserJsonString, "utf-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            exchange.getRequest().mutate().header(SecurityConstants.LOGIN_USER, loginUserJsonStringEncodeUTF8);
        }
        return chain.filter(exchange);
    }
}